# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# Author     ：skyTree
# version    ：python 3.11
# Description：角色路由
"""
from fastapi import APIRouter, HTTPException
from typing import Union

from core.Response import base_response
from core.Utils import build_tree
from curd.role import add_role_curd, update_role_curd, set_role_permission_curd, del_role_permission_curd
from models.base import Role
from schemas.role import RoleSchema, RoleOutSchema, RoleEditSchema, RoleSetOrDelPermissionSchema, MenuSchema, \
    RoleCreateSchema
from schemas.base import BaseResponse, DetailBaseResp

role_router = APIRouter(prefix="/roles")


@role_router.post("", summary="添加角色", response_model=Union[RoleOutSchema, BaseResponse])
async def role_add(role: RoleCreateSchema):
    try:
        role = await add_role_curd(role)
        return base_response(200, "添加角色成功!", data=role)
    except HTTPException as e:
        return base_response(code=str(e).split(":")[0], msg=str(e).split(":")[1])
    except Exception as e:
        return base_response(code=500, msg=f"添加角色失败！失败原因为:{e}")


@role_router.delete("/{id}", summary="删除角色", response_model=BaseResponse)
async def role_del(id: int):
    role = await Role.get_or_none(id=id).prefetch_related("menus")
    if not role:
        return base_response(code=422, msg="角色不存在!")
    # 删除关联的菜单数据
    await role.menus.clear()
    # 确保菜单数据已经被删除
    await role.save()
    # 删除角色
    await role.delete()
    return base_response(200, "删除角色成功!")


@role_router.put("", summary="编辑角色", response_model=Union[RoleOutSchema, BaseResponse])
async def role_edit(role: RoleEditSchema):
    try:
        role_dict = await update_role_curd(role)
        return base_response(200, "编辑角色成功!", data=role_dict)
    except HTTPException as e:
        return base_response(code=str(e).split(":")[0], msg=str(e).split(":")[1])
    except Exception as e:
        return base_response(code=500, msg=f"编辑角色失败！失败原因为:{e}")


@role_router.get("", summary="角色列表", response_model=DetailBaseResp)
async def role_get():
    roles = await Role.all().prefetch_related("menus")

    # 将查询结果转换为字典形式
    role_data = []
    for role in roles:
        role_menus = [MenuSchema(**dict(menu)).dict() for menu in role.menus]
        menus_tree = build_tree(role_menus)
        role_dict = RoleSchema(id=role.id, name=role.name, desc=role.desc, menus=menus_tree)
        role_data.append(role_dict)
    return base_response(200, "获取角色列表成功!", data=role_data)


@role_router.post("/set_per", summary="设置角色权限", response_model=Union[RoleOutSchema, BaseResponse])
async def role_set_per(post: RoleSetOrDelPermissionSchema):
    try:
        role = await set_role_permission_curd(post)
        return base_response(200, "设置角色权限成功!", role)
    except HTTPException as e:
        return base_response(code=str(e).split(":")[0], msg=str(e).split(":")[1])
    except Exception as e:
        return base_response(code=500, msg=f"设置角色权限失败！失败原因为:{e}")


@role_router.post("/del_per", summary="删除角色权限", response_model=Union[RoleOutSchema, BaseResponse])
async def role_del_per(post: RoleSetOrDelPermissionSchema):
    try:
        role = await del_role_permission_curd(post)
        return base_response(200, "删除角色权限成功!", role)
    except HTTPException as e:
        return base_response(code=str(e).split(":")[0], msg=str(e).split(":")[1])
    except Exception as e:
        return base_response(code=500, msg=f"删除角色权限失败！失败原因为:{e}")
